package com.ethan.auth.extention;

import com.ethan.excetion.BizException;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import static com.ethan.enums.BizCodeEnum.CODE_ERROR;

/**
 * @Description: TODO
 * @Author ethan
 * @CreateDate:2022/3/23 15:15
 * @UpdateDate: 2021/6/17 08:52
 * @Version 1.0
 */
@Data
public class SystemProvider implements AuthenticationProvider {
    private UserDetailServceImpl userDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String tel = (String) authentication.getPrincipal();
        String code = (String) authentication.getCredentials();
        if (!"888".equals(code)){
              throw new BizException(CODE_ERROR);
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(tel);
        if (userDetails==null){
            throw new BizException(CODE_ERROR);
        }
        SystemToken systemToken = new SystemToken(userDetails.getAuthorities(),userDetails,userDetails.getPassword());
        systemToken.setDetails(authentication.getDetails());
        return systemToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.isAssignableFrom(SystemToken.class);
    }
}
